package org.seata.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.seata.entity.Money;
import org.seata.service.IMoneyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author kingdom
 * @since 2020-10-16
 */
@RestController
@RequestMapping("/money")
public class MoneyController {

    @Autowired
    private IMoneyService moneyService;


    @PostMapping(value = "/insertMoney")
    public String insertMoney() {
        try {
            Money money = new Money();
            money.setMoney(BigDecimal.valueOf(10000))
                    .setAccountId("1316928406032527362");
            moneyService.save(money);
            return "SUCCESS";
        } catch (Exception e) {
            e.printStackTrace();
            return "ERROR";
        }
    }

    /**
     * 必须抛出异常，让调用者感知到异常
     * @param accountId
     * @param aount
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/feignUpdate")
    public String feignUpdate(@RequestParam(name = "accountId") String accountId,
                              @RequestParam(name = "aount") String aount) throws Exception{
        BigDecimal value = BigDecimal.valueOf(Integer.parseInt(aount));
        LambdaQueryWrapper<Money> lam = new LambdaQueryWrapper<Money>()
                .eq(Money::getAccountId, accountId);
        Money money = moneyService.getOne(lam);
        if (money.getMoney().compareTo(value) >= 0) {
            money.setMoney(money.getMoney().subtract(value));
            moneyService.updateById(money);
        }
        System.out.println(1/0);
        return "SUCCESS";

    }

}

